package com.gitee.chili.leisure.server;

import com.gitee.chili.leisure.core.ReceiverType;
import com.gitee.chili.leisure.properties.InitializeNettyProperties;
import com.gitee.chili.leisure.properties.NettyHandlerProperties;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * InitializeBootstrap
 *
 * @author week solider
 * @since 2020-07-21
 */
public class DefaultChannelInitializer extends ChannelInitializer<SocketChannel> {


    private InitializeNettyProperties initializeNettyProperties;

    private NettyHandlerProperties nettyHandlerProperties;


    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        initializeHandler(ch.pipeline());
    }

    protected void initializeHandler(ChannelPipeline channelPipeline) {
        // HttpServerCodec & HttpObjectAggregator  解析http协议
        // httpServerCodec 中创建了解码器和编码器
        channelPipeline.addLast(new HttpServerCodec());
        // HttpObjectAggregator 将 ByteBuf 解析为HttpMessage和HttpContents
        channelPipeline.addLast(new HttpObjectAggregator(initializeNettyProperties.getMaxContentLength()));
        // 对大数据流的支持
        channelPipeline.addLast(new ChunkedWriteHandler());
        // 指定服务器的目录地址
        channelPipeline.addLast(new WebSocketServerProtocolHandler(initializeNettyProperties.getSocketPath()));
        // 连接监听 可处理断线重连等
        channelPipeline.addLast(new IdleStateHandler(nettyHandlerProperties.getReaderIdleTimeSeconds(),
                nettyHandlerProperties.getWriterIdleTimeSeconds(), nettyHandlerProperties.getAllIdleTimeSeconds()));

        // ====================================  以下是自定义 =================================

        // 消息解码器
        channelPipeline.addLast(new MessageDecoder());
        // 消息编码器
        channelPipeline.addLast(new MessageEncoder());
        // 消息前置处理器
        channelPipeline.addLast(new BinaryMessageHandler());
    }

    public DefaultChannelInitializer setInitializeNettyProperties(InitializeNettyProperties initializeNettyProperties) {
        this.initializeNettyProperties = initializeNettyProperties;
        return this;
    }

    public DefaultChannelInitializer setNettyHandlerProperties(NettyHandlerProperties nettyHandlerProperties) {
        this.nettyHandlerProperties = nettyHandlerProperties;
        return this;
    }

}
